<template>
  <el-upload
    class="upload-demo"
    action="http://localhost:3001/upload-image"
    :show-file-list="false"
    :on-success="handleUploadSuccess"
    :before-upload="beforeUpload"
    :headers="{ 'Content-Type': 'multipart/form-data' }"
  >
    <el-button type="primary">上传 .glb 模型</el-button>
  </el-upload>
  <div class="model-viewer">
    <!-- Three.js 渲染区域 -->
    <div ref="threeContainer" class="canvas-container"></div>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";

const threeContainer = ref(null);

const modelUrl = ref(null);

const handleUploadSuccess = (res) => {
  modelUrl.value = res.url; // 后端返回 /uploads/xxx.glb
  loadModel(modelUrl.value);
};

const beforeUpload = (file) => {
  if (!file.name.endsWith(".glb")) {
    ElMessage.warning("请上传 .glb 格式文件");
    return false;
  }
  return true;
};

function loadModel(url) {
  const loader = new GLTFLoader();
  loader.load(
    url,
    (gltf) => {
      const model = gltf.scene;
      scene.add(model);
      // 可复用前面的居中 + 缩放逻辑
    },
    undefined,
    (err) => {
      console.error("❌ 模型加载失败", err);
    }
  );
}

onMounted(() => {
  // 初始化场景
  const scene = new THREE.Scene();

  // 添加相机
  const camera = new THREE.PerspectiveCamera( //透视相机，模拟人眼视角
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
  );
  camera.position.set(2, 2, 4);

  // 添加渲染器
  const renderer = new THREE.WebGLRenderer({ antialias: true }); //WebGL渲染器，将3D场景绘制到canvas上
  renderer.setSize(window.innerWidth, window.innerHeight);
  threeContainer.value.appendChild(renderer.domElement);

  // 添加光源
  const light = new THREE.AmbientLight(0xffffff, 1);
  scene.add(light);

  // 添加控制器
  const controls = new OrbitControls(camera, renderer.domElement); //使用OrbitControls实现模型旋转/缩放/平移的鼠标控制
  controls.enableDamping = true; //enableDamping: true 启用惯性效果，操作更流畅

  // 加载模型
  const loader = new GLTFLoader();
  loader.load("/src/public/models/tesla_m3_model.glb", (gltf) => {
    scene.add(gltf.scene);

    // 自动居中和缩放
    const model = gltf.scene;
    const box = new THREE.Box3().setFromObject(model); //计算模型包围盒(Box3)
    const center = box.getCenter(new THREE.Vector3()); //获取模型中心点和尺寸
    const size = box.getSize(new THREE.Vector3());
    // 模型居中
    model.position.sub(center);

    // 根据尺寸调整相机距离（粗略）
    const maxDim = Math.max(size.x, size.y, size.z);
    camera.position.set(0, maxDim, maxDim);
    camera.lookAt(0, 0, 0);

    controls.update();
  });

  // 控制渲染循环
  function animate() {
    requestAnimationFrame(animate);
    controls.update();
    renderer.render(scene, camera);
  }
  animate();
});
</script>

<style scoped>
.model-viewer {
  width: 100%;
  height: 100vh;
  overflow: hidden;
}
.canvas-container {
  width: 100%;
  height: 100%;
}
</style>
